package com.mokairui.threadpool.juc.count_down_latch;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description 不会重用, 减法(一次性,用完需要重新再创建)
 * @Author Mokairui
 * @Since 2021/10/7
 */
@Slf4j(topic = "c.countDownLatch")
public class CountDownLatchDemo {
    public static void main(String[] args) {
        CountDownLatch latch = new CountDownLatch(3);
        ExecutorService service = Executors.newFixedThreadPool(4);

        service.submit(() -> {
            log.debug("begin...");
            sleep(1000);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        });

        service.submit(() -> {
           log.debug("begin...");
           sleep(1500);
           latch.countDown();
           log.debug("end...{}", latch.getCount());
        });

        service.submit(() -> {
            log.debug("begin...");
            sleep(2000);
            latch.countDown();
            log.debug("end...{}", latch.getCount());
        });

        service.submit(() -> {
            try {
                log.debug("waiting...");
                latch.await();
                log.debug("wait end...");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }


    public static void sleep(int mills) {
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
